﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using geetol.sms.core;
using System.Data;

namespace geetol.sms.service.task
{
    public class smsKeMai : taskBase
    {

        SendConfig sendconfig;
        weimei_sms_api smsapi;
        List<core.entity.smsconfig> smsconfig;
        core.entity.smsvar smsvar;

        public smsKeMai()
        {
            sendconfig = LoadSendConfig();
            smsvar = config.LoadSmsVar();
            smsapi = new weimei_sms_api();
        }

        SendConfig LoadSendConfig()
        {
            var s = config.ReadFile("kemai_sendconfig.txt");
            if (string.IsNullOrEmpty(s))
                return new SendConfig();
            return Serialize.FromJson<SendConfig>(s);
        }

        void SaveSendConfig()
        {
            var s = Serialize.ToJson(sendconfig);
            config.WriterFile("kemai_sendconfig.txt", s);
        }

        protected override void PerformTasks()
        {
            smsconfig = config.getSmsContent();
            var conAdd = smsconfig.FirstOrDefault(o => o.smskey == "新增会员");
            if (conAdd != null)
            {
                if (conAdd.smsSend)
                {
                    //增加会员卡触发信息
                    string sqlstr = "select oper_date,card_id,card_type,vip_name,vip_sex,vip_tel,card_balance,vip_integral,total_integral from pos_t_vip_info";
                    sqlstr += " where oper_date > '" + sendconfig.addvip + "'";
                    if (invalidTime > 0)
                        sqlstr += " and oper_date > '" + DateTime.Now.AddMinutes(-invalidTime) + "'";
                    try
                    {
                        DataTable dt = DbHelperSQL.Query(sqlstr).Tables[0];
                        sms_send(dt, conAdd);
                    }
                    catch (Exception ex)
                    {
                        log.Write(ex);
                    }
                }
            }
            conAdd = smsconfig.FirstOrDefault(o => o.smskey == "会员储值");
            if (conAdd != null)
            {
                if (conAdd.smsSend)
                {
                    string sqlstr = "select vc.flow_id,vc.oper_date,vc.card_cost,vi.card_id,vi.card_type,vi.vip_name,vi.vip_sex,vi.vip_tel,vi." +
                        "card_balance,vi.vip_integral,vi.total_integral from pos_t_vip_cost vc ";
                    sqlstr += " join pos_t_vip_info vi on vi.card_id = vc.card_id";
                    sqlstr += " where card_way = '充值' and  vc.flow_id > " + sendconfig.vipsto;

                    if (invalidTime > 0)
                        sqlstr += " and vc.oper_date > '" + DateTime.Now.AddMinutes(-invalidTime) + "'";
                    try
                    {
                        DataTable dt = DbHelperSQL.Query(sqlstr).Tables[0];
                        sms_send(dt, conAdd);
                    }
                    catch (Exception ex)
                    {
                        log.Write(ex);
                    }
                }
            }
            conAdd = smsconfig.FirstOrDefault(o => o.smskey == "会员消费");
            if (conAdd != null)
            {
                if (conAdd.smsSend)
                {
                    string sqlstr = "select vc.flow_id,vc.oper_date,vc.card_cost,vi.card_id,vi.card_type,vi.vip_name,vi.vip_sex,vi.vip_tel,vi." +
                        "card_balance,vi.vip_integral,vi.total_integral from pos_t_vip_cost vc ";
                    sqlstr += " join pos_t_vip_info vi on vi.card_id = vc.card_id";
                    sqlstr += " where card_way = '消费' and  vc.flow_id > " + sendconfig.vipsale;

                    if (invalidTime > 0)
                        sqlstr += " and vc.oper_date > '" + DateTime.Now.AddMinutes(-invalidTime) + "'";
                    try
                    {
                        DataTable dt = DbHelperSQL.Query(sqlstr).Tables[0];
                        sms_send(dt, conAdd);
                    }
                    catch (Exception ex)
                    {
                        log.Write(ex);
                    }
                }
            }
        }

        /*
         * 会员信息表pos_t_vip_info
card_id	char	20	卡号
card_type	char	2	卡类别
vip_name	varchar	30	卡姓名
vip_sex	char	2	性别
vip_tel	varchar	16	手机号
card_balance	numeric	9	卡余额
vip_integral	numeric	9	当前积分
total_integral	numeric	9	累积积分
oper_date       创建时间

            *会员消费，储值表pos_t_vip_cost
         */

        void sms_send(DataTable dt, core.entity.smsconfig smsconfig)
        {
            var svar = smsvar.varlist.FirstOrDefault(o => o.smskey == smsconfig.smskey);
            int sms_type = 0;
            switch (smsconfig.smskey)
            {
                case "新增会员":
                    sms_type = 1;
                    break;
                case "会员储值":
                    sms_type = 2;
                    break;
                case "会员消费":
                    sms_type = 3;
                    break;
                default:
                    break;
            }
            foreach (DataRow dr in dt.Rows)
            {
                //取的手机号码
                string mobile = dr["vip_tel"] as string;
                var dtime = dr["oper_date"] as DateTime?;
                if (mobile.Length == 11)
                {
                    //组合内容
                    string txt = smsconfig.smsValue;
                    if (svar != null)
                    {
                        foreach (var smsv in svar.smsvar)
                        {
                            try
                            {
                                var str = dr[smsv.Value].ToString();
                                if (!string.IsNullOrEmpty(str)) str = str.Trim();
                                txt = txt.Replace("{{" + smsv.Key + "}}", str);
                            }
                            catch { }
                        }
                    }
                    //发送这条信息
                    var r = smsapi.SendSMS(mobile, txt);
                    insertLogs(r, mobile, txt, sms_type);
                }
                if (sms_type == 1)
                    sendconfig.addvip = dtime.Value.AddSeconds(1).ToString("yyyy-MM-dd HH:mm:ss");
                else if (sms_type == 2)
                    sendconfig.vipsto = Convert.ToInt32(dr["flow_id"]);
                else if (sms_type == 3)
                    sendconfig.vipsale = Convert.ToInt32(dr["flow_id"]);
            }
            SaveSendConfig();
        }

        void insertLogs(weimei_sms_api.res_SendSMS r, string mobile, string sms_msg, int sms_type)
        {
            //写入日记
            string insert = string.Format("insert into gt_sms_sendLog (ctime,mobile,sms_txt,sms_type,taskid,sms_res_stat,sms_res_msg) values " +
                "(getdate(),'{0}','{1}',{2},'{3}','{4}','{5}') ", mobile, sms_msg, sms_type, r.taskid, r.status, r.returnmsg);
            DbHelperSQL.ExecuteSql(insert);
        }

        public class SendConfig
        {
            /// <summary>
            /// 增加会员 最大ID
            /// </summary>
            public string addvip = DateTime.Now.AddYears(-100).ToString("yyyy-MM-dd HH:mm:ss");
            /// <summary>
            /// 会员销售 最大ID
            /// </summary>
            public int vipsale = 0;
            /// <summary>
            /// 会员储值 最大ID
            /// </summary>
            public int vipsto = 0;
        }
    }
}
